package com.lishe.lishe.lishe.module.auth.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.AutoScrollHelper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.lishe.lishe.lishe.module.auth.fragment.AuthBaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhcase on 2017/9/5.
 * 为ViewPager添加布局（Fragment），绑定和处理fragments和viewpager之间的逻辑关系
 * <p>
 * When using FragmentPagerAdapter or FragmentStatePagerAdapter, it is best to deal solely with getItem() and not touch instantiateItem() at all. The instantiateItem()-destroyItem()-isViewFromObject() interface on PagerAdapter is a lower-level interface that FragmentPagerAdapter uses to implement the much simpler getItem() interface.
 * <p>
 * Before getting into this, I should clarify that
 * <p>
 * if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.
 * An earlier version of this answer made the mistake of using FragmentPagerAdapter for its example - that won't work because FragmentPagerAdapter never destroys a fragment after it's been displayed the first time.
 * <p>
 * I don't recommend the setTag() and findViewWithTag() workaround provided in the post you linked. As you've discovered, using setTag() and findViewWithTag() doesn't work with fragments, so it's not a good match.
 * <p>
 * The right solution is to override getItemPosition(). When notifyDataSetChanged() is called, ViewPager calls getItemPosition() on all the items in its adapter to see whether they need to be moved to a different position or removed.
 * <p>
 * By default, getItemPosition() returns POSITION_UNCHANGED, which means, "This object is fine where it is, don't destroy or remove it." Returning POSITION_NONE fixes the problem by instead saying, "This object is no longer an item I'm displaying, remove it." So it has the effect of removing and recreating every single item in your adapter.
 * <p>
 * This is a completely legitimate fix! This fix makes notifyDataSetChanged behave like a regular Adapter without view recycling. If you implement this fix and performance is satisfactory, you're off to the races. Job done.
 * <p>
 * If you need better performance, you can use a fancier getItemPosition() implementation. Here's an example for a pager creating fragments off of a list of strings:
 * <p>
 * public int getItemPosition(Object item) {
 * MyFragment fragment = (MyFragment)item;
 * String title = fragment.getTitle();
 * int position = titles.indexOf(title);
 * <p>
 * if (position >= 0) {
 * return position;
 * } else {
 * return POSITION_NONE;
 * }
 * }
 * <p>
 * 以下是解决问题关键。
 * <p>
 * or those who still face the same problem which i faced before when i have viewpager with seven fragments.
 * the default for these fragments to load the english content from service but the problem here
 * that i want to change the language from settins activity and after finish Settings activity i want viewpager in main activity
 * to refresh the fragments to match the langauge selection from the user and load the arabic content
 * if user choose arabic here what i did to work from the first time
 * <p>
 * <p>
 * 1-you must use vFragmentStatePagerAdapter as mentioned above.
 * <p>
 * 2-on mainActivity i overrided the onResume and did the following
 * <p>
 * if (!(mPagerAdapter == null)) {
 * <p>
 * mPagerAdapter.notifyDataSetChanged();
 * <p>
 * <p>
 * }
 * 3-i ovveride the getItemPosition() in mPagerAdapter and make it return POSITION_NONE.
 *
 * @Override public int getItemPosition(Object object) {
 * <p>
 * return POSITION_NONE;
 * }
 * works like charm
 * <p>
 * 注：
 * FragmentStatePagerAdapter 和前面的 FragmentPagerAdapter 一样，是继承子 PagerAdapter。
 * 但是，和 FragmentPagerAdapter 不一样的是，正如其类名中的 'State' 所表明的含义一样，
 * 该 PagerAdapter 的实现将只保留当前页面，当页面离开视线后，就会被消除，释放其资源；而在页面需要显示时，
 * 生成新的页面(就像 ListView 的实现一样)。这么实现的好处就是当拥有大量的页面时，不必在内存中占用大量的内存
 */

public class FragmentViewPagerAdapter extends FragmentStatePagerAdapter implements ViewPager.OnPageChangeListener {

    private static final String TAG = FragmentViewPagerAdapter.class.getSimpleName();

    private List<AuthBaseFragment> fragments; // 每个Fragment对应一个Page
    private List<AuthBaseFragment> fragmentsStack = new ArrayList<AuthBaseFragment>();

    private AuthBaseFragment rootFragment;

    private Activity mContext;

    private FragmentManager fragmentManager;

    private ViewPager mViewPager;

    public FragmentViewPagerAdapter(Activity ctx, FragmentManager fragmentManager, List<AuthBaseFragment> fragments, ViewPager viewPager) {
        super(fragmentManager);
        this.mContext = ctx;
        this.fragments = fragments;
        this.fragmentManager = fragmentManager;
        this.mViewPager = viewPager;
    }


    private boolean isForward = false;

    public void gotoFragmentForward(int fragmentIndex) {
        isForward = true;
        AuthBaseFragment f = this.fragments.get(fragmentIndex);
        fragmentsStack.add(f);
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Log.e(TAG,"2fragmentsStack.size():"+fragmentsStack.size());
                notifyDataSetChanged();
                //Log.e(TAG,"3fragmentsStack.size():"+fragmentsStack.size());
                mViewPager.setCurrentItem(fragmentsStack.size() - 1, true);


            }
        });
    }

    private boolean isBack = false;

    public void gotoFragmentBack(final int fragmentIndex) {
        isBack = true;


        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (fragmentIndex == 0) {
                    mViewPager.setCurrentItem(0);
                } else {
                    mViewPager.setCurrentItem(fragmentsStack.size() - 2);
                }

            }
        });

    }

    @Override
    public int getCount() {
        return fragmentsStack.size();
    }


//
//    @Override
//    public long getItemId(int position) {
//        //return super.getItemId(position);
//        Log.e(TAG,"getItemId. pos:"+position+"   tag:"+(fragmentsStack.get(position)).getTAG());
//
//        return fragmentsStack.get(position).getId();
//    }

    @Override
    public int getItemPosition(Object object) {
        //return POSITION_NONE;
        int position = fragmentsStack.indexOf(object);


        //Log.e(TAG,"getItemPosition:"+((AuthBaseFragment)object).getTAG()+"   pos："+position);
//        if (position > 0) {
//            return POSITION_NONE;
//        } else if(position == 0) {
//            return 0;
//        } else
//        {
//            return POSITION_NONE;
//        }

//        if (position >= 0) {
//            return position;
//        } else {
//            return POSITION_NONE;
//        }

        return POSITION_NONE;

    }

    @Override
    public Fragment getItem(int position) {

        //Log.e(TAG,"getItem:"+position);

        return (AuthBaseFragment) fragmentsStack.get(position);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

//        Log.e(TAG," onPageScrolled.position:"+position+"  positionOffset:"+positionOffset+"   positionOffsetPixels:"+positionOffsetPixels);
//       if(position == (fragmentsStack.size()-2))
//       {
//           //Log.e(TAG," onPageScrolled.position:"+position);
//
//           mContext.runOnUiThread(new Runnable() {
//               @Override
//               public void run() {
//                   fragmentsStack.remove(fragmentsStack.size()-1);
//                   notifyDataSetChanged();
//               }
//           });
//       }
    }

    @Override
    public void onPageSelected(int i) {
//        Log.e(TAG,"onPageSelected:"+i);
//        for(AuthBaseFragment ff :fragmentsStack)
//        {
//            Log.e(TAG," onPageSelected leave:"+ff.getTag());
//        }

//        if(isForward)
//        {
//            mContext.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    int index = fragmentsStack.size()-1;
//                    final AuthBaseFragment f = fragmentsStack.get(index);
////
//
//
//                    if(fragmentManager.findFragmentByTag(f.getTag())!=null)
//                    {
//                        Log.e(TAG,"存在："+f.getTag());
////                        FragmentTransaction ft = fragmentManager.beginTransaction();
////                        ft.add(f,f.getTag());
////                        ft.commit();
////
////                        fragmentManager.executePendingTransactions();
//                    }else
//                    {
//                        Log.e(TAG,"不存在："+f.getTag());
////                        FragmentTransaction ft = fragmentManager.beginTransaction();
////                        ft.add(f,f.getTag());
////                        ft.commit();
////
////                        fragmentManager.executePendingTransactions();
//                    }
//
//
//
//                    for(AuthBaseFragment ff :fragmentsStack)
//                    {
//                        Log.e(TAG," leave:"+ff.getTag());
//                    }
//                    notifyDataSetChanged();
//                    mViewPager.destroyDrawingCache();
//                }
//            });
//
//            isForward = false;
//        }

    }

    @Override
    public void onPageScrollStateChanged(int i) {

        //Log.e(TAG,"onPageScrollStateChanged:"+i);
        if (i == 0 && isBack) {

            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mViewPager.getCurrentItem() == 0) {
                        int c = fragmentsStack.size();
                        for (int i = c - 1; i > 0; i--) {
                            fragmentsStack.remove(i);
                            notifyDataSetChanged();
                        }

                    } else {
                        int index = fragmentsStack.size() - 1;
                        //                       final AuthBaseFragment f = fragmentsStack.get(index);
//

//                    FragmentTransaction ft = fragmentManager.beginTransaction();
//                    ft.remove(f);
//                    ft.commit();
//                    fragmentManager.executePendingTransactions();

//                    if(fragmentManager.findFragmentByTag(f.getTag())!=null)
//                    {
//                        Log.e(TAG,"存在："+f.getTag());
//                    }else
//                    {
//                        Log.e(TAG,"不存在："+f.getTag());
//                    }
                        fragmentsStack.remove(index);
//
//
////                    for(AuthBaseFragment ff :fragmentsStack)
////                    {
////                        Log.e(TAG," leave:"+ff.getTag());
////                    }
                        notifyDataSetChanged();
                        //mViewPager.destroyDrawingCache();
                    }

                }
            });

            isBack = false;
        }

    }


    /**
     * page切换额外功能接口
     */
    public static class OnExtraPageChangeListener {

        public void onExtraPageScrolled(int i, float v, int i2) {
        }

        public void onExtraPageSelected(int i) {
        }

        public void onExtraPageScrollStateChanged(int i) {
        }
    }


}